package com.hcc.gateway.netty.filter;

import com.hcc.gateway.netty.context.GatewayExchange;
import com.hcc.gateway.netty.context.RespContext;
import com.hcc.gateway.netty.support.ByteBufUtils;
import com.hcc.gateway.netty.support.GatewayConstants;
import com.hcc.gateway.netty.support.GatewayResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * WriteRespFilter
 *
 * @author shengjun.hu
 * @date 2021/12/28
 */
@Slf4j
@Component
public class WriteRespFilter implements GatewayFilter {

    @Override
    public int getOrder() {
        return GatewayConstants.ORDER + 3;
    }

    @SneakyThrows
    @Override
    public void filter(GatewayExchange exchange, GatewayFilterChain chain) {
        log.info("进入WriteRespFilter !");

        RespContext respContext = exchange.getRespContext();
        GatewayResponse response = exchange.getAttributeByName(GatewayConstants.GATEWAY_RESPONSE_ATTR, GatewayResponse.class);

        respContext.setHttpStatus(HttpResponseStatus.valueOf(response.getHttpCode()));
        response.getHeaders().forEach((k, v) -> respContext.getHeaders().add(k, v));
        if (response.getBody() != null) {
            respContext.setBody(ByteBufUtils.writeByteToByteBuf(response.getBody()));
        }
    }

}
